package com.li.configserve.config.redis;

import com.li.configserve.domain.properties.RedisProperties;
import com.li.toolkit.constant.LogConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


/**
 * @Description：
 * @Author：LiDong
 * @Create：2020/8/18
 * @Version：1.0.0
 */
@Configuration
public class JedisConfig {

    private final Logger logger = LoggerFactory.getLogger(JedisConfig.class);

    @Autowired
    RedisProperties redisProperties;

    /**
     * jedisPool初始化
     */
    @Bean
    public JedisPool getJedisPool() {
        try {
            JedisPoolConfig poolConfig = new JedisPoolConfig();
            poolConfig.setMaxTotal(Integer.parseInt(redisProperties.getPool().get("maxActive")));
            poolConfig.setMaxIdle(Integer.parseInt(redisProperties.getPool().get("maxIdle")));
            //注意单位是ms，要转换单位
            poolConfig.setMaxWaitMillis(Integer.parseInt(redisProperties.getPool().get("maxWait")) * 1000L);
            poolConfig.setMinIdle(Integer.parseInt(redisProperties.getPool().get("minIdle")));
            JedisPool jedisPool = new JedisPool(poolConfig, redisProperties.getHost(), redisProperties.getPort(),
                    redisProperties.getTimeout() * 1000, redisProperties.getPassword(), 0);

            jedisPool.getResource().set("test", "redis Connect test OK!");
            String test = jedisPool.getResource().get("test");
            logger.info(LogConst.LOG_SUCCESS_PREFIX + test);
            logger.info(LogConst.LOG_SUCCESS_PREFIX + "JedisPool初始化完成...");
            return jedisPool;
        } catch (Exception e) {
            logger.error(LogConst.LOG_FAILURE_PREFIX + "JedisPool初始化失败！" + e.getMessage());
            return null;
        }
    }
}
